package com.ywx.yypicturebackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.model.GetObjectRequest;
import com.ywx.yypicturebackend.api.aliyunai.AliyunAiService;
import com.ywx.yypicturebackend.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.ywx.yypicturebackend.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.ywx.yypicturebackend.api.aliyunai.model.Input;
import com.ywx.yypicturebackend.common.BaseResponse;
import com.ywx.yypicturebackend.common.ResultUtils;
import com.ywx.yypicturebackend.constant.FileConstant;
import com.ywx.yypicturebackend.constant.UserConstant;
import com.ywx.yypicturebackend.exception.BusinessException;
import com.ywx.yypicturebackend.exception.ErrorCode;
import com.ywx.yypicturebackend.exception.ThrowUtils;
import com.ywx.yypicturebackend.manager.CosManager;
import com.ywx.yypicturebackend.manager.upload.FilePictureUpload;
import com.ywx.yypicturebackend.manager.upload.PictureUploadTemplate;
import com.ywx.yypicturebackend.manager.upload.UrlPictureUpload;
import com.ywx.yypicturebackend.mapper.PictureMapper;
import com.ywx.yypicturebackend.model.dto.file.UploadPictureResult;
import com.ywx.yypicturebackend.model.dto.picture.*;
import com.ywx.yypicturebackend.model.entity.Picture;
import com.ywx.yypicturebackend.model.entity.Space;
import com.ywx.yypicturebackend.model.entity.User;
import com.ywx.yypicturebackend.model.enums.PictureReviewStatusEnum;
import com.ywx.yypicturebackend.model.vo.PictureVO;
import com.ywx.yypicturebackend.model.vo.UserVO;
import com.ywx.yypicturebackend.service.PictureService;
import com.ywx.yypicturebackend.service.SpaceService;
import com.ywx.yypicturebackend.service.UserService;
import com.ywx.yypicturebackend.utils.ColorSimilarUtils;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ywx
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2025-05-13 19:30:38
 */
@Service
@NoArgsConstructor
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureService {
    @Resource
    AliyunAiService aliyunAiService;

    @Resource
    FilePictureUpload filePictureUpload;

    @Resource
    UrlPictureUpload urlPictureUpload;

    @Resource
    UserService userService;

    @Resource
    SpaceService spaceService;

    @Resource
    CosManager cosManager;

    @Resource
    TransactionTemplate transactionTemplate;


    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);

        Long spaceId = pictureUploadRequest.getSpaceId();
        Space space = null;

        //如果有spaceId,判断空间是否存在
        if (spaceId != null) {
            space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            //判断该空间是否为当前登录用户创建
            if (!space.getUserId().equals(loginUser.getId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有该空间权限!");
            }
        }


        //用于判断是上传新图片还是修改图片
        Long pictureId = null;
        boolean isUpload = pictureUploadRequest.getId() == null ? true : false;

        Picture oldPicture = null;
        //如果是修改图片,判断图片是否存在
        if (!isUpload) {
            pictureId = pictureUploadRequest.getId();
            oldPicture = this.getById(pictureId);

            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);

            //只有本人或者管理员可以修改
            if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }

            //校验空间是否一致
            //如果没传spaceId 则复用原图的spaceId
            if (spaceId == null) {
                spaceId = oldPicture.getSpaceId();
            } else {
                //传了spaceId，那么必须和原图一致
                if (ObjectUtil.notEqual(spaceId, oldPicture.getSpaceId())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间id不一致");
                }

                //校验额度
                if (space.getTotalCount() >= space.getMaxCount()) {
                    throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间条数不足");
                }
                if (space.getTotalSize() >= space.getMaxSize()) {
                    throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间大小不足");
                }


            }
        }

        //判断是通过文件上传还是URL上传
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if (inputSource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }

        String uploadFilePathPreFix;
        if (spaceId == null) {
            //如果此时spaId仍然为空,则为添加或修改到公共图库
            uploadFilePathPreFix = String.format(FileConstant.PUBLIC_PATH + "%s", loginUser.getId());
        } else {
            uploadFilePathPreFix = String.format(FileConstant.SPACE_PATH + "%s", spaceId);
        }

        //上传图片
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputSource, uploadFilePathPreFix);

        ///构造要入库的Picture
        Picture picture = new Picture();

        //设置压缩图片路径,原图路径,缩略图片路径
        picture.setUrl(uploadPictureResult.getUrl());
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
        picture.setOriginalUrl(uploadPictureResult.getOriginalUrl());


        String picName = uploadPictureResult.getPicName();
        if (pictureUploadRequest != null && StrUtil.isNotBlank(pictureUploadRequest.getPicName())) {
            picName = pictureUploadRequest.getPicName();
        }

        picture.setName(picName);
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setUserId(loginUser.getId());
        picture.setSpaceId(spaceId);
        picture.setPicColor(uploadPictureResult.getPicColor());
        //如果是更新
        if (!isUpload) {
            //设置图片id字段
            picture.setId(pictureId);
            picture.setEditTime(new Date());
            //删除原来COS中的压缩图和缩略图以及原图。
//            clearPictureFile(oldPicture);  在数据库修改后删除后再做删除
        }

        //无论更新还是修改,填充审核字段
        this.fileReviewParams(picture, loginUser);

        //开启事务
        Long finalSpaceId = spaceId;
        Picture finalOldPicture = oldPicture;
        transactionTemplate.execute(status -> {
            boolean saveOrUpdate = this.saveOrUpdate(picture);//根据是否具有id属性判断是更新还是新增
            ThrowUtils.throwIf(!saveOrUpdate, ErrorCode.OPERATION_ERROR, "图片上传失败");


            //如果上传到非公共图库,更新额度
            if (finalSpaceId != null) {
                //如果是更新
                if (!isUpload) {

                    boolean update = spaceService.lambdaUpdate().eq(Space::getId, finalSpaceId)
                            .setSql("totalSize = totalSize + " + (picture.getPicSize() - finalOldPicture.getPicSize()))//修改则减去原来的图片大小
                            .update();
                    ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "图片上传失败,额度更新失败");
                    //删除原来COS中的压缩图和缩略图以及原图。
                    clearPictureFile(finalOldPicture);
                } else {
                    //如果是上传
                    boolean update = spaceService.lambdaUpdate().eq(Space::getId, finalSpaceId)
                            .setSql("totalCount = totalCount +1")
                            .setSql("totalSize = totalSize + " + picture.getPicSize())
                            .update();
                    ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "图片上传失败,额度更新失败");
                }
            }

            return picture;
        });


        return PictureVO.objToVO(picture);
    }


    @Override
    public void checkPictureAuth(Picture picture, User loginUser) {
        Long spaceId = picture.getSpaceId();
        if (spaceId == null) {
            //是公共的图片,仅管理员或创建者可以有权限操作
            if (!(userService.isAdmin(loginUser) || picture.getUserId().equals(loginUser.getId()))) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        } else {
            //是某个空间的图片,仅空间创建者或空间管理员可操作
            if (!picture.getUserId().equals(loginUser.getId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }

    }

    @Override
    public void deletePicture(User loginUser, Long pictureId) {
        ThrowUtils.throwIf(pictureId == null || pictureId <= 0, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);

        //判断图片是否存在
        Picture oldPicture = this.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);

        //权限校验
        checkPictureAuth(oldPicture, loginUser);


        transactionTemplate.execute(status -> {
            //删除图片
            boolean deleteResult = this.removeById(pictureId);

            ThrowUtils.throwIf(!deleteResult, ErrorCode.OPERATION_ERROR);

            if (oldPicture.getSpaceId() != null) {//如果是删除空间中的图片
                //更新额度
                boolean update = spaceService.lambdaUpdate().eq(Space::getId, oldPicture.getSpaceId())
                        .setSql("totalCount = totalCount - 1")
                        .setSql("totalSize = totalSize - " + oldPicture.getPicSize())
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "图片删除失败,额度更新失败");
            }
            //异步清理文件
            this.clearPictureFile(oldPicture);


            return true;
        });


    }


    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, User loginUser) {
        //将DTO转换成实体类
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        //将list转换成String
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        //设置编辑时间
        picture.setEditTime(new Date());

        //数据校验
        this.validPicture(picture);

        //判断图片是否存在
        Long id = pictureEditRequest.getId();
        Picture oldPicture = this.getById(id);

        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);


        //校验权限
        checkPictureAuth(oldPicture, loginUser);

        //填充审核字段
        this.fileReviewParams(picture, loginUser);

        //操作数据库
        boolean result = this.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    /**
     * 批量抓取图片
     *
     * @param pictureUploadByBatchRequest
     * @param loginUser
     * @return
     */
    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        ThrowUtils.throwIf(pictureUploadByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        String searchText = pictureUploadByBatchRequest.getSearchText();

        //指定图片名称前缀
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
        if (StrUtil.isBlank(namePrefix)) {
            //如果没有指定名称前缀,则默认搜索关键词为前缀
            namePrefix = searchText;
        }

        //限制一次抓取的数量
        Integer count = pictureUploadByBatchRequest.getCount();
        ThrowUtils.throwIf(count > 30, ErrorCode.PARAMS_ERROR, "一次最多抓取30条");
        //要抓取的地址
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);

        Document document = null;

        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("页面获取失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取页面失败");
        }

        Element div = document.getElementsByClass("dgControl").first();

        if (ObjectUtil.isNull(div)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取元素失败");
        }

        //观察网页结构,拿到所有图片标签元素
//        Elements imgElements = div.select("img.mimg");
        Elements imgElements = div.select(".iusc");

        //记录上传成功的数量
        int upLoadCount = 0;

        //遍历元素,依次上传
        for (Element imgElement : imgElements) {
//            String fileUrl = imgElement.attr("src");

            //获取data-m属性中的JSON字符串
            String dataM = imgElement.attr("m");
            String fileUrl = "";

            try {
                //解析JSON字符串
                JSONObject jsonObject = JSONUtil.parseObj(dataM);
                //获取原始图片URL
                fileUrl = jsonObject.getStr("murl");
            } catch (Exception e) {
                log.info("解析图片失败", e);
                continue;
            }


            if (StrUtil.isBlank(fileUrl)) {
                log.info("当前连接为空,已跳过: {}", fileUrl);
                continue;
            }
            //处理图片上传地址,防止出现转移问题
            //Url示例:
            // https://tse3-mm.cn.bing.net/th/id/OIP-C.sPgwHtYKbg6cTN5LBYF_nQHaEK?w=309&amp;h=180&amp;c=7&amp;r=0&amp;o=5&amp;pid=1.7

            //截掉问号后的数据
//            int questionMarkIndex = fileUrl.indexOf("?");
//            fileUrl = fileUrl.substring(0, questionMarkIndex);

            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            pictureUploadRequest.setFileUrl(fileUrl);

            //设置名称名称,序号连续递增。
            pictureUploadRequest.setPicName(namePrefix + (upLoadCount + 1));

            try {
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                log.info("图片上传成功: id = {}", pictureVO.getId());
                upLoadCount++;
                if (upLoadCount >= count) {
                    break;
                }
            } catch (Exception e) {
                log.info("图片Url上传失败", e);
            }

        }

        return null;
    }

    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);

        //审核的照片id不能为空,要修改的审核状态值不能为空,不能修改成代审核状态
        if (id == null || reviewStatusEnum == null || PictureReviewStatusEnum.REVIEWING.equals(reviewStatusEnum)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //判断要修改的图片是否存在
        Picture oldPicture = getById(id);
        if (oldPicture == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        //判断是否已经是该状态
        if (oldPicture.getReviewStatus().equals(reviewStatusEnum.getValue())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请勿重复审核");
        }

        //修改审核状态
        //需要使用新的Picture对象而不是oldPicture,防止修改所有字段
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureReviewRequest, picture);
        picture.setReviewerId(loginUser.getId());
        picture.setReviewTime(new Date());
        boolean updateResult = updateById(picture);

        ThrowUtils.throwIf(!updateResult, ErrorCode.OPERATION_ERROR);

    }


    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();

        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();//多字段搜索
        Long userId = pictureQueryRequest.getUserId();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        Long reviewerId = pictureQueryRequest.getReviewerId();

        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();

        //编辑时间查询条件
        java.sql.Date startEditTime = pictureQueryRequest.getStartEditTime();
        java.sql.Date endEditTime = pictureQueryRequest.getEndEditTime();


        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();

        //从多字段中搜索
        if (StrUtil.isNotBlank(searchText)) {//判断字符串是否不为空且不为空串组成
            queryWrapper.and(
                    qw -> qw.like("name", searchText)
                            .or()
                            .like("introduction", searchText)
            );
        }

        queryWrapper.eq(ObjectUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.isNull(nullSpaceId, "spaceId");

        //图片基本信息
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(category), "category", category);

        //图片格式信息
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.eq(ObjectUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjectUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjectUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjectUtil.isNotEmpty(picScale), "picScale", picScale);

        //审核信息
        queryWrapper.eq(ObjectUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        queryWrapper.eq(ObjectUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);

        //图片编辑信息,ge:>=  lt:<
        queryWrapper.ge(ObjectUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        queryWrapper.lt(ObjectUtil.isNotEmpty(endEditTime), "editTime", endEditTime);


        //JSON数组 标签查询
        if (ObjectUtil.isNotEmpty(tags))
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }

        //排序
        queryWrapper.orderBy(StrUtil.isNotBlank(sortField), "ascend".equals(sortOrder), sortField);


        return queryWrapper;
    }


    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {

        PictureVO pictureVO = PictureVO.objToVO(picture);
        Long userId = pictureVO.getUserId();

        if (userId != null) {
            User user = userService.getById(userId);
            UserVO userVo = userService.getUserVo(user);
            pictureVO.setUser(userVo);
        }

        return pictureVO;
    }

    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        //拿到分页结果中的数据列表
        List<Picture> pictureList = picturePage.getRecords();

        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        //如果分页数据为空,则直接返回即可
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }

        //对象列表 =》 封装对象列表
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVO).collect(Collectors.toList());


        //关联查询用户信息
        Set<Long> userIdSet = pictureList.stream().map(Picture::getId).collect(Collectors.toSet());
        //用户id映射用户对象
        Map<Long, List<User>> userIdUserListMap =
                userService.listByIds(userIdSet).stream().collect(Collectors.groupingBy(User::getId));

        //填充信息
        pictureVOList.forEach(pictureVO -> {
            long userId = pictureVO.getUserId();
            User user = null;

            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUser(userService.getUserVo(user));

        });
        pictureVOPage.setRecords(pictureVOList);

        return pictureVOPage;
    }

    @Override
    public List<Picture> getPicturesBySpaceId(Long spaceId) {
        ThrowUtils.throwIf(spaceId == null, ErrorCode.PARAMS_ERROR);
        boolean exists = spaceService.lambdaQuery().eq(Space::getId, spaceId).exists();
        ThrowUtils.throwIf(!exists, ErrorCode.NOT_FOUND_ERROR, "空间不存在");

        List<Picture> pictureList = this.lambdaQuery().eq(Picture::getSpaceId, spaceId).list();


        return pictureList;
    }

    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);

        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();

        //修改修改数据时,id不能为空,其他参数要符合规范
        ThrowUtils.throwIf(ObjectUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        //如果有传入相关参数,进行校验
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简洁过长");

        }

    }


    @Override
    public void fileReviewParams(Picture picture, User loginUser) {

        //如果是在私有空间上传或修改图片,无需审核
        if (picture.getSpaceId() != null) {
            picture.setReviewMessage("上传私有空间无需审核");
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewTime(new Date());
            picture.setReviewerId(loginUser.getId());
            return;
        }

        //如果是管理员,自动过审
        if (loginUser.getUserRole().equals(UserConstant.ADMIN_ROLE)) {
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewMessage("管理员自动过审");
            picture.setReviewTime(new Date());
            picture.setReviewerId(loginUser.getId());
        } else {
            //如果是普通用户,设置为未审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }


    }

    @Override
    public List<PictureVO> getPictureVOListByColor(Long spaceId, String color, User loginUser) {
        //1.校验参数
        ThrowUtils.throwIf(StrUtil.isBlank(color), ErrorCode.PARAMS_ERROR);
        List<Picture> pictureList;
        //2.校验空间权限
        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            ThrowUtils.throwIf(!loginUser.getId().equals(space.getUserId()), ErrorCode.NO_AUTH_ERROR);

            //查询该空间下的所有图片
            pictureList = this.lambdaQuery().eq(Picture::getSpaceId, spaceId)
                    .isNotNull(Picture::getPicColor)
                    .list();
        } else {
            //查询公共图片
            pictureList = this.lambdaQuery().isNotNull(Picture::getPicColor)
                    .isNull(Picture::getSpaceId)
                    .list();
        }
        //3.计算相似度并排序


        //如果没有图片则直接返回,无需计算
        if (CollUtil.isEmpty(pictureList)) {
            return new ArrayList<>();
        }


        //将传进来的颜色转换成Color类防止后续每次比较都进行转换
        Color targetColor = Color.decode(color);

        //排序计算
        List<Picture> sortedPictureList = pictureList.stream().sorted(Comparator.comparingDouble(picture -> {
            String hexColor = picture.getPicColor();
            Color color1 = Color.decode(hexColor);

            if (StrUtil.isBlank(hexColor)) {//没有主色调的图片设置为最大值,默认排序到底部
                return Double.MAX_VALUE;
            }

            return -ColorSimilarUtils.calculateSimilarity(targetColor, color1);
        })).limit(30).collect(Collectors.toList());

        //4.返回结果
        return sortedPictureList.stream().map(PictureVO::objToVO).collect(Collectors.toList());
    }


    @Override
    public void pictureEditByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        //1.校验参数
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();
        ThrowUtils.throwIf(CollUtil.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR, "请选择图片");
        ThrowUtils.throwIf(spaceId == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        //2.校验权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        ThrowUtils.throwIf(!loginUser.getId().equals(space.getUserId()), ErrorCode.NO_AUTH_ERROR);

        //3.获取到图片列表
        List<Picture> pictureList = this.lambdaQuery().select(Picture::getId, Picture::getSpaceId)
                .in(Picture::getId, pictureIdList)
                .eq(Picture::getSpaceId, spaceId)
                .list();

        if (pictureList.isEmpty())
            return;

        //4.修改图片信息
        pictureList.forEach(picture -> {
            if (StrUtil.isNotBlank(category)) {
                picture.setCategory(category);
            }
            if (CollUtil.isNotEmpty(tags)) {
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });

        //批量重命名
        String nameRule = pictureEditByBatchRequest.getNameRule();
        fillPictureWithNameRule(pictureList, nameRule);

        //5.修改数据库
        boolean result = this.updateBatchById(pictureList);
        ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR, "修改图片信息失败");
    }

    /**
     * name:命名规则,格式:图片{序号}
     *
     * @param pictureList
     * @param nameRule
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (CollUtil.isEmpty(pictureList) || StrUtil.isBlank(nameRule)) {
            return;
        }
        try {
            long index = 1;
            for (Picture picture : pictureList) {
                picture.setName(nameRule.replaceAll("\\{序号}", String.valueOf(index)));
            }
        } catch (Exception e) {
            log.error("命名解析错误:{}", e.getMessage());
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "命名解析失败");
        }


    }

    @Async //开启一个新的线程来执行该方法
    @Override
    public void clearPictureFile(Picture picture) {

        //判断图片是否有多个引用
        String pictureUrl = picture.getUrl();
        long count = lambdaQuery().eq(Picture::getUrl, pictureUrl).count();
        //如果该图片被多个记录使用,不删除
        if (count > 1) {
            return;
        }


        try {
            //删除压缩图
            URI compressedUri = new URI(pictureUrl);
            cosManager.deleteObject(compressedUri.getPath());

            //删除缩略图
            URI thumbnailUri = new URI(picture.getThumbnailUrl());
            String thumbnailPicKey = thumbnailUri.getPath();
            if (StrUtil.isNotBlank(thumbnailPicKey)) {
                cosManager.deleteObject(thumbnailPicKey);
            }

            //删除原图,之前数据库有的数据没有原图url,所有需要判断一下
            URI originalUri = new URI(picture.getOriginalUrl());
            String originalPicKey = originalUri.getPath();
            if (StrUtil.isNotBlank(originalPicKey)) {
                cosManager.deleteObject(originalPicKey);
            }

        } catch (URISyntaxException e) {
            log.info("图片URL获取失败,可能未完全删除图片", e);
        }


    }


    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {

        //获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        Picture picture = Optional.ofNullable(this.getById(pictureId)).orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR, "图片不存在"));

        //校验权限
        checkPictureAuth(picture, loginUser);

        //构造请求参数
        CreateOutPaintingTaskRequest request = new CreateOutPaintingTaskRequest();
        request.setModel("image-out-painting");
        Input input = new Input();
        input.setImageUrl(picture.getUrl());
        request.setInput(input);

        request.setParameters(createPictureOutPaintingTaskRequest.getParameters());
        //调用任务
        CreateOutPaintingTaskResponse outPaintingTask = aliyunAiService.createOutPaintingTask(request);

        return outPaintingTask;
    }


    @Override
    public PictureVO copyPicture(Picture source, Long targetSpaceId, User loginUser) {

        //校验参数和权限
        ThrowUtils.throwIf(source == null, ErrorCode.PARAMS_ERROR);
        if (source.getSpaceId() != null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限保存其他空间中的图片");
        }

        Space space = spaceService.getById(targetSpaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "目标空间不存在");
        ThrowUtils.throwIf(!space.getUserId().equals(loginUser.getId()), ErrorCode.NO_AUTH_ERROR,"无权限操作该空间");

        //获取源图片的url
        String url = StrUtil.isNotBlank(source.getOriginalUrl()) ? source.getOriginalUrl() : source.getUrl();

        PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
        pictureUploadRequest.setPicName(source.getName());
        pictureUploadRequest.setSpaceId(targetSpaceId);
        //通过url上传图片
        return uploadPicture(url, pictureUploadRequest, loginUser);

    }


    /**
     * 为所有图片设置主色调,只是填充图片颜色,与业务无关
     */
    @Override
    public void setPictureListColor() {
        List<Picture> pictureList = this.getBaseMapper().selectList(new QueryWrapper<Picture>());
        String bucket = cosManager.getCosClientConfig().getBucket();
        String rule = "imageAve";
        for (Picture picture : pictureList) {
            if (picture.getPicColor() != null)
                continue;

            URL url = null;
            try {
                url = new URL(picture.getUrl());
            } catch (MalformedURLException e) {
                throw new RuntimeException(e);
            }
            String s = url.getPath().replaceAll("//", "/");
            //创建获取对象的请求
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucket, s);
            //设置规则
            getObjectRequest.putCustomQueryParameter(rule, null);

            COSObject object = cosManager.getCosClient().getObject(getObjectRequest);
            COSObjectInputStream objectContent = object.getObjectContent();

            //获取内容流并解析主色调信息
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                CloseableHttpResponse httpResponse = httpClient.execute(objectContent.getHttpRequest());
                String response = EntityUtils.toString(httpResponse.getEntity());
                String rgb = JSONUtil.parseObj(response).getStr("RGB");

                picture.setPicColor(rgb);
            } catch (Exception e) {
                log.error("获取图片主色调失败", e);
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取图片主色调失败");
            }
        }
        //更新数据库
        this.saveOrUpdateBatch(pictureList);

    }
}




